package org.madgecko.web;


import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.madgecko.basic.model.User;
import org.madgecko.basic.service.iface.IUserService;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Inject
	private IUserService userService;

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		// 未登录用户跳转登录界面
		User user = (User)session.getAttribute("user");
		boolean ifDevelopModel = PropertyHolder.getBooleanProperty("config.developModel");
		// develop model session超时,则自动加入root用户
		if(ifDevelopModel==true){
			if(null==user){
				session.setAttribute("user", userService.loadByName("root"));
			}
//			return true;
		}else{
			if(null==user){
				// 检测是否是swfupload,swfupload请求无sid
				String sid = (String)request.getParameter("sid");
				if(sid!=null && !"".equals(sid.trim())){
					session = SessionContext.getSession(sid);
				}else{
//					response.sendRedirect(request.getContextPath() + "/login");
//					//必须加return,否则抛空指针异常
//					return true;

					String type = request.getHeader("x-requested-with");
					// 系统ajax请求有3类，以1最多：
					// 1.ext
					// 2.jQuery获取js文件
					// 3.dwr
					if(("XMLHttpRequest").equalsIgnoreCase(type)){
						response.addHeader("sessionstatus", "timeout");
					}else{
						response.sendRedirect(request.getContextPath() + "/login");
					}
					//必须加return,否则抛空指针异常
					return false;
				}
			}
		}
		return super.preHandle(request, response, handler);
	}

}
